# -*- coding:utf-8 -*-

"""Lire/ecrire les donnees GPS."""

import os.path
import sqlite3

ACCEPT_EXTS = [""]
ACCEPT_EXTS_EXIF = [".jpg", ".jpeg"]


#==============================================================================


def write_gps_data(f, coords, loc="db"):
    """Ecrire les donnees GPS."""
    if "db" not in loc and "exif" not in loc:
        loc = "exif" if any(f.endswith(e) for e in ACCEPT_EXTS_EXIF) else "db"
    if "exif" in loc:
        r = write_exif(f, coords)
    if "db" in loc:
        r = write_db(f, coords)
    return r


#------------------------------------------------------------------------------

def read_gps_data(f, loc="db"):
    """Lire les donnees GPS."""
    r = ["","",""]
    if "exif" not in loc:
        r = read_db(f)
    if "db" not in loc and r == ["","",""]:
        r = read_exif(f)
    return r


#==============================================================================


def write_exif(filename, coords):
    """Ecrire les donnees GPS (EXIF)."""
    print "GeoTag: write EXIF"
    return False

#------------------------------------------------------------------------------

def read_exif(filename):
    """Lire les donnees GPS (EXIF)."""
    print "GeoTag: read EXIF"
    return ["","",""]


#==============================================================================


def __init_db(filename):
    """Tests communs (BDD)."""
    dir,f = os.path.split(filename)
    db = os.path.join(dir, ".geodata")
    xf = os.path.exists(filename) and os.path.isfile(filename)
    xd = os.path.exists(db) and os.path.isfile(db)
    return [f, dir, db, xf, xd]

#------------------------------------------------------------------------------


def write_db(filename, coords):
    """Ecrire les donnees GPS (BDD)."""
    print "GeoTag: write DB"
    f, dir, db, xf, xd = __init_db(filename)
    if not(xf and any(f.endswith(e) for e in ACCEPT_EXTS)):
        return False
    cnx = None
    try:
        # Initialiser SQL
        cnx = sqlite3.connect(db)
        cnx.text_factory = str
        cur = cnx.cursor()
        # Creer table si inexistante
        if not xd:
            cur.execute('PRAGMA encoding="UTF-8"')
            cur.execute('CREATE TABLE geotags (file TEXT PRIMARY KEY, lat TEXT, lng TEXT, alt TEXT)')
        # Rechercher fichier
        cur.execute('SELECT file FROM geotags WHERE file=?', (f,))
        # Ajouter, supprimer ou mettre a jour
        if coords == ["","",""]:
            cur.execute('DELETE FROM geotags WHERE file=?', (f,))
        else:
            if cur.fetchone() is None:
                cur.execute('INSERT INTO geotags VALUES (?,?,?,?)', (f,)+tuple(coords))
            else:
                cur.execute('UPDATE geotags SET lat=?, lng=?, alt=? WHERE file=?', tuple(coords)+(f,))
        # Appliquer
        cnx.commit()
        r = True
    except:
        r = False
    finally:
        if cnx is not None:
            cnx.close()
        return r


#------------------------------------------------------------------------------

def read_db(filename):
    """Lire les donnees GPS (BDD)."""
    print "GeoTag: read DB"
    f, dir, db, xf, xd = __init_db(filename)
    if not(xf and xd):
        return ["","",""]
    cnx = None
    try:
        # Initialiser SQL
        cnx = sqlite3.connect(db)
        cnx.text_factory = str
        cur = cnx.cursor()
        # Rechercher fichier
        cur.execute('SELECT * FROM geotags WHERE file=?', (f,))
        v = cur.fetchone()
    except:
        v = None
    finally:
        if cnx is not None:
            cnx.close()
        if v is None:
            v = (f,"","","")
        return list(v[1:])


#------------------------------------------------------------------------------

def clean_db(dirname):
    """Nettoyer le fichier BDD."""
    db = os.path.join(dirname, ".geodata")
    if not(os.path.exists(db) and os.path.isfile(db)):
        return False
    # Initialiser SQL
    cnx = sqlite3.connect(db)
    cnx.text_factory = str
    cur = cnx.cursor()
    # Verifier si table existe
    cur.execute('PRAGMA encoding="UTF-8"')
    cur.execute('CREATE TABLE IF NOT EXISTS geotags (file TEXT PRIMARY KEY, lat TEXT, lng TEXT, alt TEXT)')
    # Parcourir fichiers
    cur.execute('SELECT file FROM geotags')
    for v in cur.fetchall():
        f = v[0]
        fn = os.path.join(dirname, f)
        # Supprimer fichiers inexistants
        if not(os.path.exists(fn) and os.path.isfile(fn)):
            cur.execute('DELETE FROM geotags WHERE file=?', (f,))
    # Nettoyer/compresser
    cur.execute('VACUUM')
    # Appliquer
    cnx.commit()
    cnx.close()
    return True


#==============================================================================


